<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学生信息管理</title>
  <link rel="stylesheet" href="/public/lib/element-ui/index.css">
  <script src="/public/lib/vue.js"></script>
  <script src="/public/lib/element-ui/index.js"></script>
  <script src="/public/lib/axios.min.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
      background-color: #f5f5f5;
    }
    .management-container {
      padding: 20px;
    }
    .management-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    .search-box {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
    .search-input {
      width: 200px;
      margin-right: 10px;
    }
    .table-container {
      background-color: white;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  </style>
</head>
<body>
<div id="app">
  <div class="management-container">
    <div class="management-header">
      <h3>学生信息管理</h3>
      <el-button type="primary" @click="showAddDialog = true">+ 新增</el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-box">
      <el-input
              v-model="searchKeyword"
              placeholder="请输入学号或姓名"
              class="search-input"
              @keyup.enter.native="getStudents">
      </el-input>
      <el-button type="primary" @click="getStudents">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 学生表格 -->
    <div class="table-container">
      <el-table :data="filteredStudents" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="student_id" label="学号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="gender" label="性别"></el-table-column>
        <el-table-column prop="class_name" label="班级"></el-table-column>
        <el-table-column prop="major" label="专业"></el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column prop="update_time" label="最后修改时间"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="editStudent(scope.row)">编辑</el-button>
            <el-button type="text" style="color: #F56C6C;" @click="deleteStudent(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>
    </div>
  </div>

  <!-- 新增/编辑学生对话框 -->
  <el-dialog :title="isEditing ? '编辑学生信息' : '新增学生'" :visible.sync="showAddDialog" width="500px">
    <el-form :model="studentForm" :rules="rules" ref="studentForm" label-width="80px">
      <el-form-item label="学号" prop="student_id">
        <el-input v-model="studentForm.student_id" :disabled="isEditing" placeholder="请输入学号"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="studentForm.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="studentForm.gender" placeholder="请选择性别" style="width: 100%;">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="class_name">
        <el-input v-model="studentForm.class_name" placeholder="请输入班级"></el-input>
      </el-form-item>
      <el-form-item label="专业" prop="major">
        <el-input v-model="studentForm.major" placeholder="请输入专业"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="saveStudent">{{ isEditing ? '更新' : '确定' }}</el-button>
    </div>
  </el-dialog>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        students: [],
        searchKeyword: '',
        currentPage: 1,
        pageSize: 10,
        total: 0,
        showAddDialog: false,
        isEditing: false,
        editingStudentId: null,
        studentForm: {
          student_id: '',
          name: '',
          gender: '',
          class_name: '',
          major: ''
        },
        rules: {
          student_id: [
            { required: true, message: '请输入学号', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          gender: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          class_name: [
            { required: true, message: '请输入班级', trigger: 'blur' }
          ],
          major: [
            { required: true, message: '请输入专业', trigger: 'blur' }
          ]
        }
      };
    },
    computed: {
      filteredStudents() {
        let result = this.students;

        // 搜索过滤
        if (this.searchKeyword) {
          const keyword = this.searchKeyword.toLowerCase();
          result = result.filter(student =>
                  student.student_id.toLowerCase().includes(keyword) ||
                  student.name.toLowerCase().includes(keyword)
          );
        }

        // 分页
        this.total = result.length;
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        return result.slice(start, end);
      }
    },
    mounted() {
      this.getStudents();
    },
    methods: {
      getStudents() {
        axios.get('/api/students')
                .then(response => {
                  if (response.data.success) {
                    this.students = response.data.students;
                  } else {
                    this.$message.error(response.data.message);
                  }
                })
                .catch(error => {
                  console.error('获取学生列表错误:', error);
                  this.$message.error('获取学生列表失败');
                });
      },
      resetSearch() {
        this.searchKeyword = '';
        this.currentPage = 1;
      },
      handleSizeChange(val) {
        this.pageSize = val;
      },
      handleCurrentChange(val) {
        this.currentPage = val;
      },
      editStudent(student) {
        this.isEditing = true;
        this.editingStudentId = student.id;
        this.studentForm = {
          student_id: student.student_id,
          name: student.name,
          gender: student.gender,
          class_name: student.class_name,
          major: student.major
        };
        this.showAddDialog = true;
      },
      saveStudent() {
        this.$refs.studentForm.validate((valid) => {
          if (valid) {
            if (this.isEditing) {
              // 更新学生信息
              axios.put(`/api/students/${this.editingStudentId}`, this.studentForm)
                      .then(response => {
                        if (response.data.success) {
                          this.$message.success('更新学生信息成功');
                          this.showAddDialog = false;
                          this.getStudents();
                        } else {
                          this.$message.error(response.data.message);
                        }
                      })
                      .catch(error => {
                        console.error('更新学生信息错误:', error);
                        this.$message.error('更新学生信息失败');
                      });
            } else {
              // 新增学生
              axios.post('/api/students', this.studentForm)
                      .then(response => {
                        if (response.data.success) {
                          this.$message.success('添加学生成功');
                          this.showAddDialog = false;
                          this.getStudents();
                        } else {
                          this.$message.error(response.data.message);
                        }
                      })
                      .catch(error => {
                        console.error('添加学生错误:', error);
                        this.$message.error('添加学生失败');
                      });
            }
          }
        });
      },
      deleteStudent(student) {
        this.$confirm(`确定删除学生 "${student.name}" (${student.student_id}) 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.delete(`/api/students/${student.id}`)
                  .then(response => {
                    if (response.data.success) {
                      this.$message.success('删除学生成功');
                      this.getStudents();
                    } else {
                      this.$message.error(response.data.message);
                    }
                  })
                  .catch(error => {
                    console.error('删除学生错误:', error);
                    this.$message.error('删除学生失败');
                  });
        });
      },
      resetForm() {
        this.isEditing = false;
        this.editingStudentId = null;
        this.studentForm = {
          student_id: '',
          name: '',
          gender: '',
          class_name: '',
          major: ''
        };
        if (this.$refs.studentForm) {
          this.$refs.studentForm.resetFields();
        }
      }
    },
    watch: {
      showAddDialog(val) {
        if (!val) {
          // 对话框关闭时重置表单
          this.resetForm();
        }
      }
    }
  });
</script>
</body>
</html>